package com.mbc.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mbc.config.WeChatProperties;
import com.mbc.dto.UserLoginDTO;
import com.mbc.dto.UserRealNameDTO;
import com.mbc.mapper.UserMapper;
import com.mbc.pojo.MbcUser;
import com.mbc.pojo.MbcUserInfo;
import com.mbc.service.UserService;
import com.mbc.utils.HttpClientUtil;
import com.mbc.vo.MbcUserInfoVO;
import com.mbc.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * 用户服务实现
 *
 * @author suimeng
 * @date 2024/04/08
 */
@Service
public class UserServiceImpl implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * WX 登录
     *
     * @param userLoginDTO 用户登录 DTO
     * @return {@link MbcUser}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        HashMap<String, String> map = new HashMap<>();
        //封装参数
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        //调用微信接口服务，获得当前微信用户的openid
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //解析json，获得openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new RuntimeException("微信登录失败");
        }
        //判断当前用户是否为新用户
        MbcUser user = userMapper.getByOpenid(openid);

        //如果是新用户，自动完成注册
        synchronized (this){
            if(user == null){
                user = MbcUser.builder()
                        .openid(openid)
                        .registeredDate(LocalDateTime.now())
                        .build();
                //执行注册操作
                Integer maxUserId = userMapper.getByUserId();
                if (maxUserId == null) {
                    maxUserId = 000001;
                    user.setUserId(maxUserId);
                    userMapper.insert(user);
                }else {
                    maxUserId += 1;
                    user.setUserId(maxUserId);
                    userMapper.insert(user);
                }
            }
        }

        // 使用 Sa-Token 进行登录，并返回Token
        StpUtil.login(openid);
        String tokenValue = StpUtil.getTokenValue();
        UserLoginVO build = UserLoginVO.builder()
                .openId(openid)
                .token(tokenValue)
                .build();
        //返回这个用户对象
        return build;
    }
/*    public MbcUser wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        HashMap<String, String> map = new HashMap<>();
        //封装参数
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        //调用微信接口服务，获得当前微信用户的openid
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //解析json，获得openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new RuntimeException("微信登录失败");
        }
        //判断当前用户是否为新用户
        MbcUser user = userMapper.getByOpenid(openid);

        //如果是新用户，自动完成注册
        if(user == null){
            user = MbcUser.builder()
                    .openid(openid)
                    .registeredDate(LocalDateTime.now())
                    .build();
            //执行注册操作
            Integer maxUserId = userMapper.getByUserId();
            if (maxUserId == null) {
                maxUserId = 000001;
                user.setUserId(maxUserId);
                userMapper.insert(user);
            }else {
                maxUserId += 1;
                user.setUserId(maxUserId);
                userMapper.insert(user);
            }

        }
        //返回这个用户对象
        return user;
    }*/

    /**
     * 粉丝数量
     *
     * @param userId 用户 ID
     * @return int
     */
    @Override
    public int getFansCount(String userId) {
        int count = userMapper.getFansCount(userId);
        return count;
    }

    /**
     * 获取关注数量
     *
     * @param userId 用户 ID
     * @return int
     */
    @Override
    public int getConcernCount(String userId) {
        int count = userMapper.getConcernCount(userId);
        return count;
    }

    /**
     * 更新or添加昵称
     *
     * @param userId   用户 ID
     * @param nickname 昵称
     */
    @Override
    public boolean updateNicknames(String userId, String nickname) {
        //LocalDateTime now = LocalDateTime.now();
        return userMapper.updateNicknames(userId,nickname)>0;
    }

    /**
     * 更新并添加手机号码
     *
     * @param userId      用户 ID
     * @param phoneNumber 电话号码
     * @return boolean
     */
    @Override
    public boolean updateandaddPhone(String userId, String phoneNumber) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updateandaddPhone(userId,phoneNumber,now) > 0;
    }

    /**
     * 更新或添加真实姓名
     *
     * @param userId          用户 ID
     * @param userRealNameDTO 用户真实姓名 DTO
     * @return boolean
     */
    @Override
    public boolean updateOrAddRealName(String userId, UserRealNameDTO userRealNameDTO) {
        String lastName = userRealNameDTO.getLastName();
        String firstName = userRealNameDTO.getFirstName();
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updateOrAddRealName(userId,lastName,firstName,now) > 0;
    }

    /**
     * 更新或添加详细地址
     *
     * @param userId  用户 ID
     * @param address 地址
     * @return boolean
     */
    @Override
    public boolean updateOrAddFullAddress(String userId, String address) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updateOrAddFullAddress(userId,address,now) > 0;
    }

    /**
     * 更新或添加头像
     *
     * @param userId         用户 ID
     * @param profilePicture 个人资料图片
     * @return boolean
     */
    @Override
    public boolean updateOrAddHeadShot(String userId, String profilePicture) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updateOrAddHeadShot(userId,profilePicture,now) > 0;
    }

    /**
     * 更新电子邮件
     *
     * @param userId 用户 ID
     * @param email  电子邮件
     * @return boolean
     */
    @Override
    public boolean updateEmail(String userId, String email) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updateEmail(userId,email,now) > 0;
    }

    /**g
     * 新增用户详细信息
     *
     * @param userId      用户 ID
     * @param mbcUserInfo MBC 用户信息
     * @return boolean
     */
    @Override
    public boolean insertUserInfo(String userId, MbcUserInfo mbcUserInfo) {
        String address = mbcUserInfo.getAddress();
        String lastName = mbcUserInfo.getLastName();
        String firstName = mbcUserInfo.getFirstName();
        String email = mbcUserInfo.getEmail();
        String phoneNumber = mbcUserInfo.getPhoneNumber();
        LocalDateTime dateOfBirth = mbcUserInfo.getDateOfBirth();
        String address1 = mbcUserInfo.getAddress();
        String gender = mbcUserInfo.getGender();
        String profilePicture = mbcUserInfo.getProfilePicture();
        String personalTags = mbcUserInfo.getPersonalTags();
        String personalProfile = mbcUserInfo.getPersonalProfile();
        LocalDateTime now = LocalDateTime.now();
        return userMapper.insertUserInfo(userId,address,lastName,firstName,email,phoneNumber,
                dateOfBirth,address1,gender,profilePicture,personalTags,personalProfile,now) > 0;
    }

    /**
     * 更新出生日期
     *
     * @param userId      用户 ID
     * @param dateOfBirth 出生日期
     * @return boolean
     */
    @Override
    public boolean updateDateOfBirth(String userId, String dateOfBirth) {
        return userMapper.updateDateOfBirth(userId,dateOfBirth) > 0;
    }

    /**
     * 更新个人标签
     *
     * @param userId       用户 ID
     * @param personalTags 个人标签
     * @return boolean
     */
    @Override
    public boolean updatePersonalTags(String userId, String personalTags) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updatePersonalTags(userId,personalTags,now) > 0;
    }

    /**
     * 更新或添加个人简介
     *
     * @param userId          用户 ID
     * @param personalProfile 个人简介
     * @return boolean
     */
    @Override
    public boolean updatePersonalProfile(String userId, String personalProfile) {
        LocalDateTime now = LocalDateTime.now();
        return userMapper.updatePersonalProfile(userId,personalProfile,now) > 0;
    }

    /**
     * 查询用户详细信息
     *
     * @param userId 用户 ID
     * @return {@link MbcUserInfoVO}
     */
    @Override
    public MbcUserInfoVO getByUserInfo(String userId) {
        MbcUserInfoVO mbcUserInfoVO = userMapper.getByUserInfo(userId);
        return mbcUserInfoVO;
    }


}
